package com.epfresh.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.activity.DetailGoodsActivity;
import com.epfresh.activity.HomeActivity;
import com.epfresh.activity.HomePreActivity;
import com.epfresh.activity.WebActivity;
import com.epfresh.adapter.ProductConditionAdapter;
import com.epfresh.api.utils.L;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.bean.Ad;
import com.epfresh.bean.GoodsParameters;
import com.epfresh.bean.ListGoods;
import com.epfresh.bean.ProductCondition;
import com.epfresh.constant.Constant;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.BaseFragment;
import com.epfresh.views.GoodsListView;
import com.epfresh.views.banner.SliderBanner;
import com.epfresh.views.banner.SliderBannerController;
import com.epfresh.views.dialog.BaseDialogView;
import com.epfresh.views.dialog.OnFilterClickListener;
import com.epfresh.views.dialog.ProductConditionDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wzh on 16-7-1.
 */
/*
该市场页面已不作为市场使用，在预售商品列表里有引用!
*/
public class MarketFragment extends BaseFragment {


    //ASC 顺序，DESC 倒序


    private GoodsListView goodsListView;

    private TextView tvCategory;
    private TextView tvVolume;
    private TextView tvTime;
    private ImageView ivTime;
    private ImageView ivVolume;
    private View vTime;
    private View vCategory;
    private View vVolume;
    private GoodsParameters parameters;
    private boolean isVisable = false;

    private String sortProperty;

    private List<ListGoods> list;

    private String marketId;
    private String saleType;
    private String deliveryTime;

    public boolean isNotFirst;

    private SliderBannerController sliderBannerController;
    private ViewGroup vHead;
    private int selectColor;

    public String getMarketId() {
        return marketId;
    }

    public void setMarketId(String marketId) {
        this.marketId = marketId;
    }

    public String getSaleType() {
        return saleType;
    }

    public void setSaleType(String saleType) {
        this.saleType = saleType;
    }

    public String getDeliveryTime() {
        return deliveryTime;
    }

    public void setDeliveryTime(String deliveryTime) {
        this.deliveryTime = deliveryTime;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        //判断Fragment中的ListView时候存在，判断该Fragment时候已经正在前台显示  通过这两个判断，就可以知道什么时候去加载数据了
        isVisable = getUserVisibleHint() && isVisible();
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public String getBaseTag() {
        return "marketFragment";
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        L.e("MarketFragment", "market---onActivityCreated:" + this + "---marketId=" + marketId);
        super.onActivityCreated(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        L.e("MarketFragment", "market---onCreateView:" + this + "---marketId=" + marketId);
        return inflater.inflate(R.layout.fragment_market,
                container, false);
    }

    private ViewGroup getAdHeader() {

        LayoutInflater layoutInflater = LayoutInflater.from(getContext());

        ViewGroup convertView = (ViewGroup) layoutInflater
                .inflate(
                        R.layout.ad_slider_banner,
                        null, false);


        // 图片轮播
        SliderBanner sliderBanner = (SliderBanner) convertView
                .findViewById(R.id.vp);

        View v = convertView.findViewById(R.id.slider_banner_indicator);
        v.setVisibility(View.VISIBLE);
        sliderBannerController = new SliderBannerController(getContext(),
                sliderBanner);

        int w = LocalDisplay.SCREEN_WIDTH_PIXELS;
        int h = w * 7 / 32;
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(w, h);
        convertView.setLayoutParams(lp);
        convertView.setBackgroundResource(R.drawable.def_img);
        sliderBannerController.setmClickItemListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Object tag = v.getTag(R.id.item_key_status);
                if (tag != null && tag instanceof Ad) {
                    Ad ad = (Ad) tag;

                    Intent intent = new Intent(getContext(), WebActivity.class);
                    intent.putExtra(Constant.KEY_WEB_URL, ad.getLink());
                    intent.putExtra(Constant.KEY_WEB_TITLE, ad.getTitle());
                    intent.putExtra("image_url", ad.getImg());

                    startActivity(intent);

                }

            }
        });

        LinearLayout headerParent = new LinearLayout(getContext());
        headerParent.addView(convertView);
        return headerParent;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        selectColor = getResources().getColor(R.color.green_little);
        goodsListView = (GoodsListView) view.findViewById(R.id.fragment_ptr_home_ptr_frame);
        tvCategory = (TextView) view.findViewById(R.id.tv_latest);
        tvVolume = (TextView) view.findViewById(R.id.tv_volume);
        tvTime = (TextView) view.findViewById(R.id.tv_filter);
        ivTime = (ImageView) view.findViewById(R.id.iv_filter);
        ivVolume = (ImageView) view.findViewById(R.id.iv_volume);
        vTime = view.findViewById(R.id.ll_time);
        vCategory = view.findViewById(R.id.ll_category);
        vVolume = view.findViewById(R.id.ll_volume);


        vVolume.setOnClickListener(this);
        vTime.setOnClickListener(this);
        vCategory.setOnClickListener(this);
        vCategory.setVisibility(View.GONE);


        initSortStatus();
//        tvCategory.setOnClickListener(this);
//        tvTime.setTextColor(selectColor);
//        tvCategory.setTextColor(selectColor);
        goodsListView.setBaseActivity((BaseActivity) getActivity());
        list = goodsListView.getList();
        vHead = getAdHeader();
        goodsListView.setHeadView(vHead);
        vHead.getChildAt(0).setVisibility(View.GONE);

        goodsListView.notifyDataSetChanged();
        goodsListView.setOnAdListener(new GoodsListView.OnAdListener() {
            @Override
            public void onAd(List<Ad> ads) {
                if (ads == null || ads.size() == 0) {
                    sliderBannerController.clear();
                    vHead.getChildAt(0).setVisibility(View.GONE);
                } else {
                    vHead.getChildAt(0).setVisibility(View.VISIBLE);
                    sliderBannerController.play(ads);
                }
            }
        });

        this.parameters = new GoodsParameters();
        if (marketId != null && !"".equals(marketId)) {
            List<String> marketIds = new ArrayList<>();
            marketIds.add(marketId);
            parameters.setMarketIds(marketIds);
        }

        if (deliveryTime != null && !"".equals(deliveryTime)) {
            parameters.setDeliveryTime(deliveryTime);
        }

        if (saleType != null && !"".equals(saleType)) {
//            List<String> types = new ArrayList<>();
//            types.add(saleType);
            parameters.setType(saleType);
        }

        goodsListView.setParameters(parameters);
        goodsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (goodsListView.getList().size() > i - 1 && i > 0) {
                    Intent intent = new Intent(getContext(), DetailGoodsActivity.class);
                    intent.putExtra("id", goodsListView.getList().get(i - 1).getId());
                    intent.putExtra("storeId", goodsListView.getList().get(i - 1).getStoreId());

                    intent.putExtra("promotionItemId", goodsListView.getList().get(i - 1).getPromotionItemId());
                    startActivity(intent);
                }
            }
        });

        tvTime.setText(parameters.getSortName());
        loadData();
    }

    OnFilterClickListener onFilterClickListener = new OnFilterClickListener() {
        @Override
        public void onFilter(GoodsParameters parameters) {
            if (parameters == null) {
                parameters = new GoodsParameters();
                if (marketId != null) {
                    List<String> marketIds = new ArrayList<>();
                    marketIds.add(marketId + "");
                }
            }

//            if (parameters.isFilter()) {
//                tvTime.setTextColor(selectColor);
//            } else {
//                tvTime.setTextColor(Color.parseColor("#626262"));
//
//            }
            String name = parameters.getName();
            if (name != null && !"".equals(name)) {
                tvCategory.setText(name);
                tvCategory.setTextColor(selectColor);
            }
//            if (parameters.getCategoryId() == null && parameters.getNameId() == null) {
//                tvCategory.setTextColor(Color.parseColor("#626262"));
//            } else {
//                tvCategory.setTextColor(selectColor);
//            }
//            tvCategory.setTextColor(Color.parseColor("#626262"));
//            tvVolume.setTextColor(Color.parseColor("#626262"));
            parameters.setSortProperty(sortProperty);

            parameters.setFilterName("全部分类");
            parameters.setFilterCode(null);
            parameters.setTypes(null);
            tvVolume.setTextColor(Color.parseColor("#626262"));
            MarketFragment.this.parameters = parameters;
            goodsListView.setParameters(parameters);
            goodsListView.reload();

        }
    };

    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.ll_time:
//                updateSort(v,tvTime,ivTime);
//                sort("modifiedTime");
                ivTime.setImageResource(R.mipmap.top_arrow);
                openSortDialog(1);
                break;
            case R.id.ll_category:
                if (getActivity() != null) {
                    if (getActivity() instanceof HomeActivity) {
                        ((HomeActivity) getActivity()).openProductCategory(marketId, parameters, onFilterClickListener);
                    } else if (getActivity() instanceof HomePreActivity) {
                        ((HomePreActivity) getActivity()).openProductCategory(marketId, parameters, onFilterClickListener);
                    }
                }
                break;
            case R.id.ll_volume:
//                updateSort(v,tvVolume,ivVolume);
//                sort("salesQuantity");
                ivVolume.setImageResource(R.mipmap.top_arrow);
                openSortDialog(2);
                break;
        }
    }


    public void initSortStatus() {
        //ASC 顺序，DESC 倒序,true,表示顺序,
        vVolume.setTag(R.id.item_key_status, true);
        vTime.setTag(R.id.item_key_status, true);
        tvVolume.setTextColor(Color.parseColor("#626262"));
        tvTime.setTextColor(Color.parseColor("#626262"));
        ivVolume.setImageResource(R.mipmap.bottom_arrow);
        ivTime.setImageResource(R.mipmap.bottom_arrow);
    }

    public void reSortStatus() {

//        tvVolume.setTextColor(Color.parseColor("#626262"));
//        tvTime.setTextColor(selectColor);
        ivVolume.setImageResource(R.mipmap.bottom_arrow);
        ivTime.setImageResource(R.mipmap.bottom_arrow);
    }

    

    public void updateSort(View v, TextView tv, ImageView iv) {
        Object tag = v.getTag(R.id.item_key_status);
        initSortStatus();
        boolean isAsc = false;
        if (tag != null && tag instanceof Boolean) {
            if (!((boolean) tag)) {
                isAsc = true;
            }
        }
        v.setTag(R.id.item_key_status, isAsc);
       
        tv.setTextColor(selectColor);
        if (isAsc) {
            parameters.setSortDirection("ASC");
            iv.setImageResource(R.mipmap.top_arrow);
        } else {
            parameters.setSortDirection("DESC");
            iv.setImageResource(R.mipmap.bottom_arrow);
        }


//        String sortProperty = parameters.getSortProperty();
//        if(isTime){
//            tvVolume.setTextColor(Color.parseColor("#626262"));
//            tvTime.setTextColor(selectColor);
//
//            if ("modifiedTime".equals(sortProperty)){//上次也是按时间排序的
//
//            }
//
//
//        }else {
//            tvTime.setTextColor(Color.parseColor("#626262"));
//            tvVolume.setTextColor(selectColor);
//        }
    }

    public void sort(String sortMode) {
        if (this.parameters == null)
            this.parameters = new GoodsParameters();
        this.sortProperty = sortMode;
        parameters.setSortProperty(sortMode);

        goodsListView.setParameters(parameters);
        goodsListView.reload();
    }
    public void reload() {
        goodsListView.setParameters(parameters);
        goodsListView.reload();
    }

    private void loadData() {
        goodsListView.refresh();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (isVisable) {
            firstLoadData();
        }
        L.e("MarketFragment", "market---onStart:" + this + "---marketId=" + marketId);
    }

    public void firstLoadData() {
        if (!isNotFirst) {
            goodsListView.refresh();
            isNotFirst = true;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        L.e("MarketFragment", "market---onResume:" + this + "---marketId=" + marketId);
    }

    @Override
    public void onPause() {
        super.onPause();
        L.e("MarketFragment", "market---onPause:" + this + "---marketId=" + marketId);

    }

    @Override
    public void onStop() {
        super.onStop();
        L.e("MarketFragment", "market---onStop:" + this + "---marketId=" + marketId);

    }

    @Override
    public void onDetach() {
        super.onDetach();
        L.e("MarketFragment", "market---onDetach:" + this + "---marketId=" + marketId);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        L.e("MarketFragment", "market---onDestroyView:" + this + "---marketId=" + marketId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        L.e("MarketFragment", "market---onDestroy:" + this + "---marketId=" + marketId);
    }

    ProductConditionDialog popSort;
    ProductConditionAdapter sortAdapter;
    List<ProductCondition> listSort = new ArrayList<>();

    public void openSortDialog(int type) {
        if (popSort == null) {
            popSort = new ProductConditionDialog(getContext());
            popSort.marketTop();
            GridView gv = (GridView) popSort.findViewById(R.id.gv_more);
            sortAdapter = new ProductConditionAdapter(getContext(), listSort);

            sortAdapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    String filterCode = parameters.getFilterCode();
                    if (filterCode != null && !"".equals(filterCode)){
                        tvVolume.setTextColor(selectColor);
                        tvVolume.setText(parameters.getFilterName());
                    }else{
                        tvVolume.setText("筛选");
                        tvVolume.setTextColor(Color.parseColor("#626262"));
                    }
                    String sortName = parameters.getSortName();

                    if (sortName != null && !"排序".equals(sortName)){
                        tvTime.setTextColor(selectColor);
                    }
                    tvTime.setText(sortName);
                    reload();
                    popSort.dismiss();
                }
            });
            gv.setAdapter(sortAdapter);

            popSort.setOnDismissListener(new BaseDialogView.OnDismissListener() {
                @Override
                public void onDismiss(Object o) {
                    reSortStatus();
                }
            });

        }

        if (popSort.isShowing()) {
            popSort.dismiss();
        } else {
            popSort.hideContent();
            listSort.clear();
            if (type == 1) {
                if ("排序".equals(tvTime.getText())){

                    listSort.addAll(sortAdapter.getSortCondition(true));
                }else {
                    listSort.addAll(sortAdapter.getSortCondition(false));

                }
            } else if (type == 2) {
                if (saleType != null && !"".equals(saleType)) {
                    listSort.addAll(sortAdapter.getFilterCondition(false,goodsListView.getTagList()));
                }else {
                    listSort.addAll(sortAdapter.getFilterCondition(true,goodsListView.getTagList()));
                }

                if (listSort.isEmpty()){
                    popSort.showEmpty();
                }
            }
            sortAdapter.initParameters(parameters, type);
            popSort.show();
            sortAdapter.notifyDataSetChanged();
        }
    }

    public void dismissDialog(){
        if (popSort != null && popSort.isShowing()){
            popSort.dismiss();
        }
    }

}
